package com.dge.app

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.webkit.WebView
import cat.ereza.customactivityoncrash.CustomActivityOnCrash
import cat.ereza.customactivityoncrash.config.CaocConfig
import com.blankj.utilcode.util.ProcessUtils
import com.bumptech.glide.Glide
import com.dge.app.ui.CrashActivity
import com.dge.app.ui.SplashActivity
import com.dge.common.LibApp
import com.dge.common.NdkMethods
import com.dge.common.common.UserInfoMgr
import com.dge.common.manager.ActivityStackManager
import com.tencent.mmkv.MMKV
import java.io.Serializable

@SuppressLint("StaticFieldLeak")
class APP : LibApp() {
    companion object {
        lateinit var app: APP
        lateinit var context: Context
    }

    override fun onCreate() {
        super.onCreate()
        context = this.applicationContext
        app = this
        if (isMainProcess) {
            // MMKV 初始化
            MMKV.initialize(this)
            UserInfoMgr.loadUserInfo()
            // if (AppConfig.isPublishRelease()) //测试版不验证
            NdkMethods.signatureVerify(this)
        }
        if (isMainProcess) {
            initToast()
        }
        initWebView()
        if (isMainProcess) {
            initActivityStackManger()
            //子线程初始化一些东西，优化启动时间
            Thread {
                initCrashHandler()
                // initBugly()
            }.start()
        }
    }

    private fun initActivityStackManger(): ActivityLifecycleCallbacks {
        // Activity 栈管理初始化
        val callback = ActivityStackManager.getInstance().init(this) { activity, status ->
            // if (!isBuglyInitialized && (activity is MainActivity || activity is LoginActivity)) {
            //     Timber.d("onActivityCreated  init bugly")
            //     initBugly()
            // }
        }
        return callback
    }

    private fun initCrashHandler() {
        // Crash 捕捉界面
        CaocConfig.Builder.create()
            .backgroundMode(CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM)
            .enabled(true)
            .trackActivities(false)
            .minTimeBetweenCrashesMs(2000)
            .restartActivity(SplashActivity::class.java) // 重启的 Activity
            .errorActivity(CrashActivity::class.java) // 错误的 Activity
            .eventListener(CrashEventListener())// 设置监听器
            .apply()
    }

    /***
     * 初始化WebView
     */
    private fun initWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            if (!isMainProcess) {
                WebView.setDataDirectorySuffix(ProcessUtils.getCurrentProcessName())
            }
        }
    }

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        if (level == TRIM_MEMORY_UI_HIDDEN) {
            Glide.get(this).clearMemory()
        }
        Glide.get(this).trimMemory(level)
    }

    override fun onLowMemory() {
        super.onLowMemory()
        //内存低的时候，清理Glide的缓存
        Glide.get(this).clearMemory()
    }

    //手机上不会执行
    override fun onTerminate() {
        super.onTerminate()
    }

    class CrashEventListener : CustomActivityOnCrash.EventListener, Serializable {
        val TAG = "CrashEventListener"
        override fun onLaunchErrorActivity() {
        }

        override fun onRestartAppFromErrorActivity() {
        }

        override fun onCloseAppFromErrorActivity() {
        }
    }
}